import os
import re
import sys
from pathlib import Path

def detect_encoding(file_path):
    """检测文件编码"""
    encodings = ['utf-8', 'gbk', 'gb2312', 'big5', 'latin1', 'cp1252']
    
    for encoding in encodings:
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                f.read()
            return encoding
        except UnicodeDecodeError:
            continue
    return None

def fix_encoding(file_path):
    """修复文件编码问题"""
    print(f"Processing file: {file_path}")
    
    # 检测文件编码
    encoding = detect_encoding(file_path)
    if encoding is None:
        print(f"  Could not detect encoding for {file_path}")
        return False
    
    if encoding == 'utf-8':
        print(f"  File already in UTF-8")
        return True
    
    print(f"  Detected encoding: {encoding}")
    
    try:
        # 读取原始内容
        with open(file_path, 'r', encoding=encoding) as f:
            content = f.read()
        
        # 检测非UTF-8字符并处理
        lines = content.split('\n')
        fixed_lines = []
        
        for line in lines:
            # 检查行是否包含非ASCII字符（很可能是中文注释）
            try:
                line.encode('utf-8')
                # 如果可以编码为UTF-8，保留该行
                fixed_lines.append(line)
            except UnicodeEncodeError:
                # 如果不能编码为UTF-8，删除该行（很可能是非UTF-8的中文注释）
                print(f"    Removing non-UTF-8 line: {repr(line[:50])}")
                continue
        
        # 写回文件，使用UTF-8编码
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write('\n'.join(fixed_lines))
        
        print(f"  Fixed encoding to UTF-8")
        return True
        
    except Exception as e:
        print(f"  Error fixing {file_path}: {e}")
        return False

def find_java_files(root_dir):
    """查找所有Java文件"""
    java_files = []
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            if file.endswith('.java'):
                java_files.append(os.path.join(root, file))
    return java_files

def main():
    root_dir = os.path.dirname(os.path.abspath(__file__))
    print(f"Scanning directory: {root_dir}")
    
    java_files = find_java_files(root_dir)
    print(f"Found {len(java_files)} Java files")
    
    fixed_count = 0
    error_count = 0
    
    for java_file in java_files:
        if fix_encoding(java_file):
            fixed_count += 1
        else:
            error_count += 1
    
    print(f"\nSummary:")
    print(f"  Total files: {len(java_files)}")
    print(f"  Fixed files: {fixed_count}")
    print(f"  Error files: {error_count}")

if __name__ == "__main__":
    main()